"""
视频处理，截取帧进行保存图片
"""
import cv2
from PIL import Image

def save_frame_with_exif(video_path, output_folder, start_time, end_time):
    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print("Error: Could not open video.")
        return

    # 获取视频的帧率
    fps = cap.get(cv2.CAP_PROP_FPS)
    print(f"Video FPS: {fps}")

    # 计算起始帧和结束帧
    start_frame = int(start_time * fps)
    end_frame = int(end_time * fps)

    # 设置当前帧为起始帧
    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)

    # 遍历帧并保存
    frame_count = start_frame
    while frame_count <= end_frame:
        ret, frame = cap.read()
        if not ret:
            break

        # 将 OpenCV 的 BGR 图像转换为 Pillow 的 RGB 图像
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        pil_image = Image.fromarray(frame_rgb)

        # 添加 EXIF 信息（示例：添加时间戳）
        exif_data = pil_image.getexif()
        # exif_data[306] = f"Frame Time: {frame_count / fps:.2f}s"  # 306 是 DateTime 的 EXIF 标签
        # exif_data[271] = "My Camera"  # 271 是 Make 的 EXIF 标签

        # 保存图片
        output_path = f"{output_folder}\\frame_{frame_count:05d}.jpg"
        pil_image.save(output_path, "JPEG", exif=exif_data)
        print(f"Saved: {output_path}")

        frame_count += 1

    # 释放视频对象
    cap.release()
    print("Finished saving frames.")

# 调用函数
video_path = "E:\\测试数据\\无人机正射图片数据\\DJI_20250317162606_0003_W_航点.mp4"  # 输入视频路径
output_folder = "E:\\测试数据\\无人机正射图片数据\\output_frames"  # 输出图片文件夹
start_time = 2  # 从第 2 秒开始
end_time = 39  # 到第 39 秒结束

save_frame_with_exif(video_path, output_folder, start_time, end_time)
